import * as request from '../../../utils/request';
import config from "../../../config/config";
import * as echarts from 'echarts';

export function snatchCurrentWeather(params) {
    return request.get(`${config.api.home.snatchCurrentWeather}`, params, false);
}

export function refreshStatistics(params) {
    return request.get(`${config.api.home.refreshStatistics}`, params, false);
}

export function ragModulePieChat(RAGChartRef) {
    // 初始化图表实例
    const rag_chart = echarts.init(RAGChartRef.current);

    // 配置项
    const option =  {
        title: {
            text: 'RAG检索', subtext: 'RAG模式与应用数量统计', x:'center'
        },
        tooltip: {
            trigger: 'item', formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        grid: {
            x: 50, x2: 40, y2: 30
        },
        legend: {
            orient: 'vertical', x: 'right', y: 'top', data:['文档检索', '智能检索', '特殊检索', 'RAG应用' ], padding: 20
        },
        toolbox: {
            show: false,
            feature: {
                mark: { show: true }, dataView: { show: true, readOnly: false },
                magicType: {
                    show: true, type: ['pie', 'funnel'],
                    option: {
                        funnel: {
                            x: '25%', width: '50%', funnelAlign: 'left', max: 1548
                        }
                    }
                },
                restore: { show: true },
                saveAsImage: { show: true }
            }
        },
        calculable: true,
        series: [
            {
                name: '检索统计', type: 'pie', radius: '70%', center: ['50%', '63%'],
                data:[
                    { value: 11, name: '文档检索' },
                    { value: 2, name: '智能检索' },
                    { value: 5, name: '特殊检索' },
                    { value: 2, name: 'RAG应用' }
                ]
            }
        ]
    };

    // 设置配置
    rag_chart.setOption(option);

    // 响应式（可选）
    const resizeHandler = () => rag_chart.resize();
    window.addEventListener('resize', resizeHandler);

    // 清理
    return () => {
        window.removeEventListener('resize', resizeHandler);
        rag_chart.dispose();
    };
}

export function agentModulePieChat(AgentChartRef) {
    // 初始化图表实例
    const agent_chart = echarts.init(AgentChartRef.current);

    // 配置项
    const option =  {
        title: {
            text: 'Agent智能', subtext: 'Agent模式与应用数量统计', x:'center'
        },
        tooltip: {
            trigger: 'item', formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
            orient: 'vertical', x: 'right', y: 'top', data:['智能模式', '多智能体', 'Agent应用' ], padding: 20
        },
        grid: {
            x: 50, x2: 40, y2: 30
        },
        toolbox: {
            show: false,
            feature: {
                mark: {show: true},
                dataView: {show: true, readOnly: false},
                magicType: {
                    show: true,
                    type: ['pie', 'funnel'],
                    option: {
                        funnel: {
                            x: '25%', width: '50%', funnelAlign: 'left', max: 1548
                        }
                    }
                },
                restore: {show: true},
                saveAsImage: {show: true}
            }
        },
        calculable: true,
        series: [
            {
                name: '智能统计', type: 'pie', radius: '70%', center: ['50%', '63%'],
                data: [
                    { value: 8, name: '智能模式' },
                    { value: 3, name: '多智能体' },
                    { value: 1, name: 'Agent应用' }
                ]
            }
        ]
    };

    // 设置配置
    agent_chart.setOption(option);

    // 响应式（可选）
    const resizeHandler = () => agent_chart.resize();
    window.addEventListener('resize', resizeHandler);

    // 清理
    return () => {
        window.removeEventListener('resize', resizeHandler);
        agent_chart.dispose();
    };
}

export function ragNumberTimeChat(ResponseChartRef, dialogNumbers, responseTimes) {
    // 初始化图表实例
    const response_chart = echarts.init(ResponseChartRef.current);

    const option = {
        title: {
            text: 'RAG：历史对话数量与平均响应时间', subtext: "", x:'center'
        },
        tooltip: {
            trigger: 'axis'
        },
        toolbox: {
            show: false,
            feature: {
                mark: { show: true },
                dataView: { show: true, readOnly: false },
                magicType: { show: true, type: ['line', 'bar'] },
                restore: { show: true },
                saveAsImage: { show: true }
            }
        },
        calculable: true,
        legend: {
            orient: 'horizontal', x: 'right', y: 'top', data:['历史对话数量', '平均响应时间'], padding: 20
        },
        xAxis: [
            {
                type: 'category',
                data: Object.keys(dialogNumbers),
                axisLabel: {
                    interval: 2
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                name: '历史对话数量',
                axisLabel: {
                    formatter: '{value}'
                }
            }, {
                type: 'value',
                name: '平均响应时间',
                axisLabel: {
                    formatter: '{value} s'
                }
            }
        ],
        grid: {
            x: 45, x2: 55, y: 75, y2: 30
        },
        series: [
            {
                name: '历史对话数量', type: 'bar', data: Object.values(dialogNumbers)
            }, {
                name: '平均响应时间', type: 'line', yAxisIndex: 1, data: Object.values(responseTimes)
            }
        ]
    };

    // 设置配置
    response_chart.setOption(option);

    // 响应式（可选）
    const resizeHandler = () => response_chart.resize();
    window.addEventListener('resize', resizeHandler);

    // 清理
    return () => {
        window.removeEventListener('resize', resizeHandler);
        response_chart.dispose();
    };
}

export function agentNumberTimeChat(ResponseChartRef, dialogNumbers, responseTimes) {
    // 初始化图表实例
    const response_chart = echarts.init(ResponseChartRef.current);

    const option = {
        title: {
            text: 'Agent：历史对话数量与平均响应时间', subtext: "", x:'center'
        },
        tooltip: {
            trigger: 'axis'
        },
        toolbox: {
            show: false,
            feature: {
                mark: { show: true },
                dataView: { show: true, readOnly: false },
                magicType: { show: true, type: ['line', 'bar'] },
                restore: { show: true },
                saveAsImage: { show: true }
            }
        },
        calculable: true,
        legend: {
            orient: 'horizontal', x: 'right', y: 'top', data: ['历史对话数量', '平均响应时间'], padding: 20
        },
        xAxis: [
            {
                type: 'category',
                data: Object.keys(dialogNumbers),
                axisLabel: {
                    interval: 1
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                name: '历史对话数量',
                axisLabel: {
                    formatter: '{value}'
                }
            }, {
                type: 'value',
                name: '平均响应时间',
                axisLabel: {
                    formatter: '{value} s'
                }
            }
        ],
        grid: {
            x: 45, x2: 55, y: 75, y2: 30
        },
        series: [
            {
                name: '历史对话数量', type: 'bar', data: Object.values(dialogNumbers)
            }, {
                name: '平均响应时间', type: 'line', yAxisIndex: 1, data: Object.values(responseTimes)
            }
        ]
    };

    // 设置配置
    response_chart.setOption(option);

    // 响应式（可选）
    const resizeHandler = () => response_chart.resize();
    window.addEventListener('resize', resizeHandler);

    // 清理
    return () => {
        window.removeEventListener('resize', resizeHandler);
        response_chart.dispose();
    };
}

export function processHistoryMemory(history_records, memory_details) {
    let numbers = {}, times = {};
    let source_patterns = Object.keys(history_records);
    for (let i = 0; i < source_patterns.length; i++) {
        let number = 0, time = 0;
        let history_key = source_patterns[i];
        let source_ids = history_records[history_key];
        for (let j = 0; j < source_ids.length; j++) {
            let source_id = source_ids[j];
            let detail = memory_details[source_id];
            number += detail["number"]
            time += detail["time"]
        }

        numbers[history_key] = number;
        times[history_key] = parseInt(time / number);
    }

    let ragDialogNumbers = {}, ragResponseTimes = {};
    buildMemoryDialog("rag_patterns", "retrieval", numbers, times, ragDialogNumbers, ragResponseTimes);
    buildMemoryDialog("rag_advances", "advance", numbers, times, ragDialogNumbers, ragResponseTimes);
    buildMemoryDialog("rag_specials", "special", numbers, times, ragDialogNumbers, ragResponseTimes);
    let rag_children = config.menu_side["rag"].find(item => item.name == "RAG应用")?.children || [];
    buildMemoryProgram(rag_children, numbers, times, ragDialogNumbers, ragResponseTimes);

    let agentDialogNumbers = {}, agentResponseTimes = {};
    buildMemoryDialog("agent_patterns", "answer", numbers, times, agentDialogNumbers, agentResponseTimes);
    buildMemoryDialog("agent_advances", "agentic", numbers, times, agentDialogNumbers, agentResponseTimes);
    let agent_children = config.menu_side["agent"].find(item => item.name == "Agent应用")?.children || [];
    buildMemoryProgram(agent_children, numbers, times, agentDialogNumbers, agentResponseTimes);

    console.log("processHistoryMemory ragDialogNumbers => ", ragDialogNumbers);
    console.log("processHistoryMemory ragResponseTimes => ", ragResponseTimes);
    console.log("processHistoryMemory agentDialogNumbers => ", agentDialogNumbers);
    console.log("processHistoryMemory agentResponseTimes => ", agentResponseTimes);
    return { ragDialogNumbers, ragResponseTimes, agentDialogNumbers, agentResponseTimes };
}

function buildMemoryDialog(typeKey, source, numbers, times, dialog_numbers, response_times) {
    let array = config[typeKey];
    for (let k = 0; k < array.length; k++) {
        let key = source + "-" + array[k].key;
        let objKey = array[k].key;
        dialog_numbers[objKey] = numbers[key] ? numbers[key] : 0;
        response_times[objKey] = times[key] ? times[key] : 0;
    }
}

function buildMemoryProgram(children, numbers, times, dialog_numbers, response_times) {
    for (let m = 0; m < children.length; m++) {
        let item = children[m];
        let keys = Object.keys(numbers).filter(obj => obj.includes(item.key));
        let total_number = 0, total_time = 0;
        for (let n = 0; n < keys.length; n++) {
            total_number += numbers[keys[n]];
            total_time += times[keys[n]];
        }
        dialog_numbers[item.key] = total_number;
        response_times[item.key] = parseInt(total_time / keys.length);
    }
}
